import { ExecutionContext, Injectable, BadRequestException } from '@nestjs/common';
import { AuthGuard } from "@nestjs/passport";
import { validateOrReject } from "class-validator";
import { CredentialDto } from "../dto/user.dto";
import { plainToClass } from "class-transformer";


@Injectable()
export class LocalGuard extends AuthGuard('local'){
    async CanActivate(context:ExecutionContext){
        const request=context.switchToHttp().getRequest()
        try {
            await validateOrReject(plainToClass(CredentialDto,request.body),{
                validationError:{target:false}
            })
        } catch (error) {
             const messages=(error as any [])
             messages.map(item=>{
                return item.constraints ??{}
             }).reduce((o,s)=>{
                return {...o,...s}
             },{})


             throw new BadRequestException(Object.values(messages))
        }
        return super.canActivate(context) as boolean;
    }
}